#include "server.h"
#include <QDebug>


Server::Server(QObject *parent)
    : QObject{parent}
{
    m_runningFlag = true;
}

void Server::listening()
{
    qDebug() << "server: start working.";
    m_serverFd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (m_serverFd < 0)
    {
        qDebug() << "server: create socket failed.";
        emit serverStatus(0);
        return;
    }
    struct sockaddr_in serverSock;
    bzero(&serverSock, sizeof(serverSock));
    serverSock.sin_family = AF_INET;
    serverSock.sin_port = htons(PORT);
    inet_aton("127.0.0.1", &serverSock.sin_addr);
    int err;
    err = ::bind(m_serverFd, (struct sockaddr*)&serverSock, sizeof(serverSock));
    if (err < 0)
    {
        qDebug() << "server: bind failed.";
        emit serverStatus(0);
        return;
    }
    err = ::listen(m_serverFd, MAX_BACKLOG);
    if (err < 0)
    {
        qDebug() << "server: listen failed.";
        emit serverStatus(0);
        return;
    }
    emit serverStatus(m_serverFd);
    return;
}

void Server::accepting()
{
    qDebug() << "server: start accept.";
    while (m_runningFlag)
    {
        int clientFd;
        struct sockaddr_in clientAddr;
        socklen_t addrLen;
        clientFd = ::accept(m_serverFd, (struct sockaddr*)&clientAddr, &addrLen);
        if (clientFd < 0)
        {
            qDebug() << "server: accept failed.";
            emit acceptStatus(-1);
            return;
        }
        qDebug() << "server: accept client:" << clientFd;
        emit acceptStatus(clientFd);
    }
    return;
}

void Server::stopAccept()
{
    qDebug() << "server set runningFlag false.";
    m_runningFlag = false;
}

